/*
 * 本地数据mock
 * @author li.xiaomei
 * @date 2016-12-19
 */
var url = require('url')
var path = require('path');
var fs = require('fs')

module.exports = function(req, res, next){
  var mock_config = global.think_config.mock;
  var url = req.originalUrl.split('?')[0];

  var mockDataFile = path.join(process.cwd(), mock_config.directory, url) +
    "."+mock_config.type;

  //console.log(mockDataFile)
  //file exist or not
  fs.access(mockDataFile, fs.F_OK, function(err) {
    if (err) {
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify({
        "status": "没有找到此文件",
        "notFound": mockDataFile
      }));

      console.log('【本地mock数据】出错啦~');
      next();
      return;
    }
    var data = fs.readFileSync(mockDataFile, 'utf-8');
    res.setHeader('Content-Type', 'application/json');
    res.end(data);
  });

}
